package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R addCategory(@RequestBody Category category){
        categoryService.save(category);
        return R.success(null);
    }

    @GetMapping("/page")
    public R selectByPage(Integer page,Integer pageSize){
        IPage<Category> pageinfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        categoryService.page(pageinfo,lqw);
        List<Category> records = pageinfo.getRecords();
        long total = pageinfo.getTotal();
        Map<Object, Object> data = new HashMap<>();
        data.put("records",records);
        data.put("total",total);
        return R.success(data);
    }

    @DeleteMapping
    public R deleteCategory(Long id){
        //categoryService.removeById(id);

        categoryService.remove(id);

        return R.success("删除成功");
    }

    @PutMapping
    public R updateCategory(@RequestBody Category category){
        categoryService.updateById(category);

        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R getCategory(Integer type){

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(type != null,Category::getType,type);
        lqw.orderByAsc(Category::getType);
        List<Category> list = categoryService.list(lqw);
        if(!list.isEmpty()){
            return R.success(list);
        }
        return R.error("");
    }

}
